<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>存储空间 - 首页</title>
    <base href="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${pageContext.request.contextPath}/">
    <link type="text/css" rel="stylesheet" href="static/css/style.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', sans-serif;
        }

        body {
            background-color: #f5f7fa;
        }

        #header {
            background-color: #2c3e50;
            color: white;
            padding: 1rem 2rem;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }

        .wel_word {
            font-size: 1.8rem;
            font-weight: 600;
        }

        #main {
            /*max-width: 1200px;*/
            margin: 2rem auto;
            padding: 2rem;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
        }

        #bookTable {
            width: 100%;
            border-collapse: collapse;
            margin-top: 1.5rem;
        }

        #bookTable thead {
            background-color: #f8f9fa;
        }

        #bookTable th,
        #bookTable td {
            padding: 1rem;
            border-bottom: 1px solid #e9ecef;
            text-align: left;
        }

        #bookTable th {
            font-weight: 600;
            color: #343a40;
            background: #2980b9;
        }

        #page_nav {
            margin-top: 2rem;
            text-align: center;
        }

        #page_nav a {
            display: inline-block;
            padding: 0.5rem 1rem;
            margin: 0 0.3rem;
            background-color: #3498db;
            color: white;
            text-decoration: none;
            border-radius: 4px;
            transition: background-color 0.3s;
        }

        #page_nav a:hover {
            background-color: #2980b9;
        }

        #page_nav input[type="number"] {
            padding: 0.4rem 0.8rem;
            margin: 0 0.3rem;
            border: 1px solid #ddd;
            border-radius: 4px;
            width: 60px;
        }

        #page_nav input[type="button"] {
            padding: 0.5rem 1rem;
            background-color: #2c3e50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .table th {
            text-align: center;
            vertical-align: middle;
        }

        /* 搜索框样式 */
        .search-container {
            display: flex;
            align-items: center;
            margin-bottom: 1rem;
        }

        .search-input {
            padding: 0.1rem;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-right: 0.5rem;
            flex-grow: 1;
            max-width: 300px;
        }

        .search-button {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 0.5rem 1rem;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .search-button:hover {
            background-color: #2980b9;
        }

        html, body {
            height: 100%;        /* 占据整个视口高度 */
            margin: 0;           /* 移除默认边距 */
            padding: 0;          /* 移除默认内边距 */
            overflow-x: hidden;  /* 防止水平滚动 */
        }

        .read-only-radio input[type="radio"] {
            cursor: not-allowed;
            opacity: 0.6; /* 使单选按钮稍微透明以显示不可用状态 */
        }

        .read-only-radio span {
            color: #6c757d;
        }

        /* 表格行悬停效果 */
        .data-row:hover {
            background-color: #f8f9fa;
            transition: background-color 0.2s;
        }

        /* 按钮样式优化 */
        .btn {
            padding: 0.4rem 0.8rem;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.2s;
        }

        .btn-success {
            background-color: #2ecc71;
            color: white;
            border: none;
        }

        .btn-success:hover {
            background-color: #27ae60;
        }

        .search-container {
            display: flex;
            align-items: center;
            margin-bottom: 1rem;
            gap: 1px; /* 设置所有元素之间的默认间距为5px */
        }

        /* 调整搜索按钮和重置按钮之间的间距为1px */
        #searchBtn + #resetBtn {
            margin-left: 1px;
        }

        /* 为添加按钮添加右侧间距，确保与输入框间隔5px */
        #addOss {
            margin-right: 10px;
        }

        .search-input {
            padding: 0.5rem 1rem;
            border: 1px solid #ced4da;
            border-radius: 0.375rem;
            font-size: 0.875rem;
            line-height: 1.5;
            color: #495057;
            background-color: #fff;
            background-clip: padding-box;
            transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
            width: 100%;
            max-width: 300px;
            margin-right: 0.5rem;
            box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.075);  /* 内阴影效果 */
        }

        .search-input:focus {
            border-color: #3498db;
            outline: 0;
            box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
        }
    </style>
</head>
<body>

<div id="header">
    <span class="wel_word">云存储空间管理</span>
</div>

<div id="main">

    <div id="book">
        <table id="bookTable" class="table">
            <thead>
            <tr>
                <th colspan="8" style="background: #fff;">
                    <div class="search-container">
                        <button class="search-button" id="addOss" type="button" onclick="window.location.href='pages/oss/oss_edit.jsp'">
                            添加存储空间
                        </button>
                        <input type="text" id="searchKeyword" class="search-input" placeholder="请输入存储空间名称">
                        <button id="searchBtn" class="search-button">搜索</button>
                        <button id="resetBtn" class="search-button" style="background-color: #e74c3c;">重置</button>
                    </div>
                </th>
            </tr>
            <tr>
                <th style="text-align: center;">存储空间编号</th>
                <th style="text-align: center;">存储空间名称</th>
                <th style="text-align: center;">存储类型</th>
                <th style="text-align: center;">容量</th>
                <th style="text-align: center;">流量</th>
                <th style="text-align: center;">当月访问次数</th>
                <th style="text-align: center;">访问权限</th>
                <th style="text-align: center;">操作</th>
            </tr>
            </thead>
            <tbody>
            <tr class="b_list" style="display: none;">
                <td>
                    <div class="oss_id"></div>
                </td>
                <td>
                    <div class="oss_name"></div>
                </td>
                <td>
                    <div class="oss_type"></div>
                </td>
                <td>
                    <div class="oss_capacity"></div>
                </td>
                <td>
                    <div class="oss_flow"></div>
                </td>
                <td>
                    <div class="oss_visits"></div>
                </td>
                <td>
                    <div class="oss_permission"></div>
                </td>
                <td>
                    <button class="btn btn-success updateOss" type="button" ossId="">修改</button>
                </td>
            </tr>
            </tbody>
        </table>
    </div>

    <div id="page_nav" class="mt-4">
        <a href="javascript:void(0)" class="page-link" onclick="mypage('首页')">首页</a>
        <a href="javascript:void(0)" class="page-link" onclick="mypage('上一页')">上一页</a>
        <a href="javascript:void(0)" class="page-link" onclick="mypage('下一页')">下一页</a>
        <a href="javascript:void(0)" class="page-link" onclick="mypage('末页')">末页</a>

        <span class="ml-3">共 <strong id="totalPages"></strong> 页，</span>
        <span>总计 <strong id="totalRecords"></strong> 条记录</span>

        <span class="ml-3">
            跳转到第
            <input type="number" min="1" id="pn_input" class="ml-1" />
            页
            <button id="butid" class="ml-1">确定</button>
        </span>
    </div>
</div>

<div id="bottom" class="bg-dark text-white text-center py-2 mt-4">
    <span>
        云存储空间管理系统 &copy; ${year}
    </span>
</div>

<script src="static/script/jquery-3.6.0.min.js"></script>
<script src="static/layui/layui.js"></script>
<script>
    var peipage;
    var currentSearchKeyword = ''; // 存储当前搜索关键词

    function showOssMessage(bookName, count) {
        $("#bookCount").text(count);
        $("#bookName").text(bookName);
        $("#ossdiv").addClass('active').show().delay(3000).fadeOut();
    }

    function mypage(flag, keyword = currentSearchKeyword) {
        var pageNo;
        if (flag === '首页') pageNo = 1;
        else if (flag === '上一页') pageNo = peipage?.pageNo - 1 || 1;
        else if (flag === '下一页') pageNo = peipage?.pageNo + 1 || 1;
        else if (flag === '末页') pageNo = peipage?.pageTotal || 1;
        else pageNo = parseInt(flag);

        if (isNaN(pageNo) || pageNo < 1) pageNo = 1;

        // 存储当前搜索关键词
        currentSearchKeyword = keyword;
        $("#searchKeyword").val(keyword);

        $.ajax({
            url: "OssServlet",
            type: "POST",
            data: {method: 'searchPage', pageNo: pageNo, name: keyword},
            dataType: "json",
            beforeSend: () => layer.load(1),
            success: (msg) => {
                peipage = msg;
                $("#totalPages").text(msg.pageTotal);
                $("#totalRecords").text(msg.pageTotalCount);

                $("#bookTable tbody tr:not(.b_list)").remove();

                if (msg.items && msg.items.length > 0) {
                    msg.items.forEach(item => {
                        // 克隆模板行，移除隐藏样式和b_list类
                        const newRow = $(".b_list").clone()
                            .removeAttr('style')
                            .removeClass('b_list')
                            .addClass('data-row');


                        // 填充数据
                        newRow.find('.oss_id').text(item.id);
                        newRow.find('.oss_name').text(item.bucketName);
                        newRow.find('.oss_type').text(item.type || '标准存储');
                        // newRow.find('.oss_capacity').text(formatBytes(item.capacity));
                        // newRow.find('.oss_flow').text(formatBytes(item.flow));
                        newRow.find('.oss_capacity').text(item.capacity +"byte");
                        newRow.find('.oss_flow').text(item.flow+"byte");
                        newRow.find('.oss_visits').text(item.visits || '0');

                        // 权限选项常量
                        const permissions = [
                            { value: '私有(Pr)', text: '私有(Pr)' },
                            { value: '公共读(R)', text: '公共读(R)' },
                            { value: '公共读写(RW)', text: '公共读写(RW)' }
                        ];

                        // 创建权限选择器容器
                        const radioGroup = $('<div class="permission-selector"></div>');

                        permissions.forEach(perm => {
                            const isChecked = item.permission === perm.value;
                            const radioContainer = $('<div class="flex items-center mb-1"></div>');
                            // 创建单选按钮元素
                            const radioInput = $('<input type="radio">')
                                .attr({
                                    name: 'permission_' + item.id,
                                    value: perm.value,
                                })
                                .prop('checked', isChecked)
                                .on('change', function() {
                                    savePermissionChange(item.id, $(this).val());
                                });
                            // 创建标签元素
                            const radioLabel = $('<span>').text(perm.text);
                            // 组装并添加到容器
                            radioContainer.append(radioInput, radioLabel);
                            radioGroup.append(radioContainer);
                        });

                        // 添加到表格行
                        newRow.find('.oss_permission').html(radioGroup);
                        // 添加到表格
                        $("#bookTable tbody").append(newRow);
                        // 保存权限修改的函数
                        function savePermissionChange(ossId, newPermission) {
                            console.log("新权限="+newPermission);
                            console.log("ID="+ossId);
                            layer.load(1);
                            $.ajax({
                                url: "OssServlet",
                                type: "POST",
                                data: {
                                    method: 'updatePermissionById',
                                    id: ossId,
                                    permission: newPermission
                                },
                                dataType: "json",
                                success: (response) => {
                                    layer.closeAll();
                                    if (response.success) {
                                        layer.msg('权限修改成功', {icon: 1, time: 2000});
                                    } else {
                                        layer.msg('权限修改失败: ' + response.message, {icon: 2, time: 2000});
                                    }
                                },
                            });
                        }
                        // 修改操作按钮
                        newRow.find('button')
                            .attr('ossId', item.id)
                            .text('修改');
                        $("#bookTable tbody").append(newRow);
                    });
                } else {
                    // 没有数据时显示空状态
                    const emptyRow = $("<tr>").append(
                        $("<td>").attr("colspan", 8).addClass("text-center py-4").text("暂无数据")
                    );
                    $("#bookTable tbody").append(emptyRow);
                }
            },
            complete: () => layer.closeAll()
        });
    }

    // 格式化字节数
    // function formatBytes(bytes, decimals = 2) {
    //     if (bytes === 0) return '0 Bytes';
    //
    //     const k = 1024;
    //     const dm = decimals < 0 ? 0 : decimals;
    //     const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
    //
    //     const i = Math.floor(Math.log(bytes) / Math.log(k));
    //
    //     return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
    // }

    $(function() {
        mypage('首页');

        // 分页按钮点击事件
        $(".page-link").on('click', function() {
            mypage($(this).text());
        });

        // 确定按钮提交
        $("#butid").on('click', function() {
            const pageNo = $("#pn_input").val();
            if (/^\d+$/.test(pageNo)) mypage(pageNo);
            else layer.msg('请输入有效的页码', {icon: 2, time: 2000});
        });

        // 修改按钮点击事件
        $(document).on('click', '.updateOss', function() {
            const id = $(this).attr('ossId');
            console.log("跳转到管理页面，ID：" + id);
            // 跳转到oss_manager.jsp页面并携带ID参数
            window.location.href = "pages/oss/oss_manager.jsp?method=getBook&id=" + encodeURIComponent(id);
        });

        // 搜索按钮点击事件
        $("#searchBtn").on('click', function() {
            const keyword = $("#searchKeyword").val().trim();
            mypage('首页', keyword);
        });

        // 重置按钮点击事件
        $("#resetBtn").on('click', function() {
            $("#searchKeyword").val('');
            mypage('首页', '');
        });

        // 回车键触发搜索
        $("#searchKeyword").on('keyup', function(e) {
            if (e.key === 'Enter') {
                $("#searchBtn").click();
            }
        });
    });
</script>
</body>
</html>